package com.netstar.xmlparser;

import java.io.StringReader;
import java.util.ArrayList;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.netstar.util.EvtLog;

public class ServerSoftwareHelper {

	public static class ServerSoftwareItem {
		public String day;
		public String imei;
		public String phone;
		public String pkg;
		public long data;
	}

	public static ArrayList<ServerSoftwareItem> parse(String xml) {
		return new ContentParser().parse(xml);
	}

	private static class ContentParser extends DefaultHandler {

		private ServerSoftwareItem mItem;

		private StringBuilder mBuilder;

		private static final String TAG = "ServerSoftwareHelper.ContentParser";

		private ArrayList<ServerSoftwareItem> mItems = new ArrayList<ServerSoftwareItem>();

		public ArrayList<ServerSoftwareItem> parse(String xml) {
			if (null == xml || xml.length() == 0) {
				return mItems;
			}
			SAXParserFactory spf = SAXParserFactory.newInstance();
			try {
				StringReader sReader = new StringReader(xml);
				SAXParser parser = spf.newSAXParser();
				parser.parse(new InputSource(sReader), this);
			} catch (Exception e) {
				EvtLog.w(TAG, e.getMessage());
			}
			return mItems;
		}

		@Override
		public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
			if (localName.equals("datas")) {
				mBuilder = new StringBuilder();
			} else if (localName.equals("item")) {
				mItem = new ServerSoftwareItem();
			}
		}

		@Override
		public void endElement(String uri, String localName, String qName) throws SAXException {
			final String value = mBuilder.toString().trim();
			if (localName.equals("item")) {
				mItems.add(mItem);
			} else if (localName.equals("cdate")) {
				mItem.day = value;
			} else if (localName.equals("imei")) {
				mItem.imei = value;
			} else if (localName.equals("mobilephone")) {
				mItem.phone = value;
			} else if (localName.equals("name")) {
				mItem.pkg = value;
			} else if (localName.equals("flowcount")) {
				try {
					mItem.data = Long.parseLong(value);
				} catch (NumberFormatException e) {
					EvtLog.e(TAG, "unexpected value " + value + " for AppInfo.data");
				}
			}
		}

		@Override
		public void characters(char[] ch, int start, int length) throws SAXException {
			mBuilder.setLength(0);
			mBuilder.append(ch, start, length);
		}
	}

}
